package com.csproj.basic.resource;

import com.codahale.metrics.annotation.Timed;
import com.csproj.basic.service.AreaService;
import com.csproj.basic.service.dto.AreaDTO;
import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.repository.PageableTools;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * REST controller for managing Areas.
 */
/**
 * 区域管理的resource
 *
 *  TODO action、service都秉承返回是什么资源就在那个资源的aciton、service里面写（比如查看uid=3的机构信息）
 *  TODO url定义遵循/api/gateway（服务名）/v1/资源名
 *  TODO 定义rap要理解资源的概念（比如图书馆的书和我借的书）
 *
 *  TODO action方法只负责控制调用，不处理具体业务。
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class AreaResource {

    private final Logger log = LoggerFactory.getLogger(AreaResource.class);

    private static final String ENTITY_NAME = "area";

    private final AreaService areaService;
    private final UserInfoService userInfoService;
    private final SysLogsService sysLogsService;

    public AreaResource(AreaService areaService,UserInfoService userInfoService,SysLogsService sysLogsService) {
        this.areaService = areaService;
        this.userInfoService = userInfoService;
        this.sysLogsService = sysLogsService;
    }

    /**
     * POST  /areas : 创建区域
     * @param areaDTO 区域DTO
     * @return
     * TODO 保存post方法
     * TODO 每个方面里面都要加try catch处理
     */
    @PostMapping("/areas")
    @Timed
    public BaseDTO createArea(@Valid @RequestBody AreaDTO areaDTO){
        AreaDTO result = areaService.saveAndGetDTO(areaDTO);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_create_area","");
        return BaseDTO.createBaseDTO().setData(result);
    }


    /**
     * PUT  /areas : 修改区域.
     * @param areaDTO 企业区域.DTO
     * @return
     */
    @PutMapping("/areas/{id}")
    @Timed
    public BaseDTO updateArea(@Valid @RequestBody AreaDTO areaDTO, @PathVariable String id) throws URISyntaxException {
        areaDTO.setId(id);
        AreaDTO result = areaService.updateAndGetDTO(areaDTO);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_update_area","");
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * GET  /areas : 区域装箱.
     * @return 区域信息
     */
    @GetMapping("/areas/all")
    @Timed
    public BaseDTO getAllAreaDTO() {
        List<AreaDTO> lists = areaService.findAllAndGetDTO();
        return BaseDTO.createBaseDTO().setFieldList(lists);
    }

    /**
     * GET  /areas : 获取区域信息.
     * @return 区域信息
     */
    @GetMapping("/areas")
    @Timed
    public BaseDTO getPageAreas(@RequestParam(value = "pageNumber",required = false) Integer pageNum,
                                     @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                     @RequestParam(value = "name",required = false) String name,
                                     @RequestParam(value = "companyId",required = false) String companyId,
                                @RequestParam(value = "areaId",required = false) String areaId
    ) {

        Pageable pageable = PageableTools.basicPage(pageNum,pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("areaId",areaId);
        map.put("warehouseId",companyId);
        BaseDTO result = areaService.findPageListAndGetDTO(map,pageable);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_view_area_list","");
        return result;
    }

    /**
     * GET  /areas/:id : 根据区域id，获取区域信息
     *
     * @param id 区域id
     * @return 区域信息
     */
    @GetMapping("/areas/{id}")
    @Timed
    public BaseDTO getArea(@PathVariable String id) {
        AreaDTO areaDTO = areaService.findOneAndGetDTO(id);
        return BaseDTO.createBaseDTO().setData(areaDTO);
    }

    /**
     * DELETE  /areas/:id : 根据id，删除区域.
     * @param id id
     * @return
     */
    @DeleteMapping("/areas/{id}")
    @Timed
    public BaseDTO deleteArea(@PathVariable String id) {
        areaService.delete(id);
        return BaseDTO.createBaseDTO().setMessage("delete_success");
    }

    /**
     * 根据集装箱ids，批量删除区域
     * @param ids ids
     * @return
     */
    @DeleteMapping("/areas/deleteAreas")
    @Timed
    public BaseDTO deleteIds(@RequestBody(required = false) String[] ids) {
        areaService.deleteIds(ids);
        return BaseDTO.createBaseDTO().setMessage("batch_delete_success");
    }

    /**
     * 上传文件
     * @param file file
     * @return
     */
    @PostMapping("/areas/uploadFile")
    @Timed
    public BaseDTO uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String filePath = areaService.uploadFile(request,file);
        Map<String,Object> map = new HashMap<>();
        map.put("url",filePath);

        return BaseDTO.createBaseDTO(map).setMessage("updload_file_success");
    }
}